/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sociesc.demoweb;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.sociesc.demoweb.dao.Dao;
import com.sociesc.demoweb.utils.DatabaseUtils;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static spark.Spark.*;
/**
 *
 * @author guilherme
 */
public class Main {
    
    
    
    
    public static void main(String[] args){
        
        try {
            Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados");
            DatabaseUtils.seedDatabase();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        get("/", (request, response) -> {
            JsonObject json = new JsonObject();
            
            try {
                Dao<User> userDao = new Dao(User.class);
                List<User> users = userDao.findAll();
                JsonArray usersJson = new JsonArray();
                for(User u : users){
                    JsonObject uJson = new JsonObject();
                    uJson.add("id", u.getId());
                    uJson.add("name", u.getName());
                    usersJson.add(uJson);
                }
                json.add("users", usersJson);
                        
            } catch (SQLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                json.add("error", ex.getMessage());
                response.status(500);
            }
            
            return json.toString();
        });
    }
    
}
